package cn.stazxr.core.aspect;

import cn.stazxr.exception.RoleAndPermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author talentestors
 * @version 1.0
 * @since 2025.11.02
 **/
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
	// 处理权限/角色不足异常
	@ExceptionHandler(RoleAndPermissionException.class)
	public ResponseEntity<Map<String, Object>> handlePermissionAndRoleException(RoleAndPermissionException ex) {
		Map<String, Object> body = new HashMap<>();
		body.put("timestamp", LocalDateTime.now());
		body.put("status", ex.getCode());
		body.put("error", "Forbidden");
		body.put("message", ex.getMessage());
		body.put("requires", ex.getRequires());
		return ResponseEntity.status(HttpStatus.FORBIDDEN).body(body);
	}


	// 兜底：处理所有未捕获异常（生产环境慎用详细信息）
	@ExceptionHandler(Exception.class)
	public ResponseEntity<Map<String, Object>> handleGenericException(Exception ex) {
		Map<String, Object> body = new HashMap<>();
		body.put("timestamp", LocalDateTime.now());
		body.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
		body.put("error", "Internal Server Error");
		body.put("message", "系统内部错误");
		log.error(ex.getMessage());
		return ResponseEntity.internalServerError().body(body);
	}
}
